<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-8-11
 * Time: 下午12:41
 * To change this template use File | Settings | File Templates.
 */
class api extends MY_Controller
{
    public function index()
    {
        //$this->load->helper('cookie');
        //var_dump(authcode(get_cookie('auth'), 'DECODE'));
        //$referer = $this->input->server('HTTP_REFERER');
        //$referer = $referer && strpos($referer, 'login/submit') !== false ? $referer : '';
        //$this->load->view('user/login', array('referer'=>$referer));
        $response = array();
		self::json_output($response, true);
    }

    public function userinfo()
    {
        $response = array();
        if($this->isLogin())
        {
            foreach(array('user_id', 'passport', 'nickname') as $key)
                $response[$key] = $this->uInfo[$key];
        }
        self::json_output($response, true);
    }

    /**
     * @name 返回昵称数据接口
     * notes:
     * 	200 昵称保存成功
     *  201 昵称已存在
     * 	403 参数不全，不予验证
     * 	404 保存昵称数据失败
     * 	406 参数验证失败
     * 	500 账号不存在
     * 	501 passport格式错误（必须包含@符号）
     */
    public function nicknameReturn()
    {
        $passPort   = trim($this->input->get_post('passport'));
       	$nickName   = trim($this->input->get_post('nickname'));
       	$clientSign  = trim($this->input->get_post('authsign'));
       	$serverSign = md5($passPort.$nickName.config_item('CLIENT_AUTH_KEY'));

       	//记录每次请求的日志
       	//$log = Hjlib_Load::Tools()->Log();
       	//$logContent = $passPort."\t".$nickName."\t".$clietSign;
       	//$log->write($logContent, 'nickname_return.log', dirPath.'/var/api/');

        $response = array('error' => '200', 'msg' => '昵称保存成功', 'code' => 'nickname_save_success');

        do {
            if (empty($passPort) || empty($nickName) || empty($clientSign))
           	{
                $response = error(403);
                break;
           	}

           	if ($clientSign != $serverSign)
           	{
                $response = error(406);
                break;
           	}

            /*
           	if (strpos($passPort, '@') == false)
           	{
                   $response = error(501);
                   break;
           	}
            //*/

           	$this->load->model('user/Model_User', 'user');
           	$userInfo = $this->user->getUserInfoByPassport($passPort);

           	if (empty($userInfo) || !is_array($userInfo))
           	{
                   $response = error(500);
                   break;
           	}

           	$NUserInfo    = $this->user->getUserByNickName($nickName);
           	if (!empty($NUserInfo))
           	{
                   $response = error(201);
                   break;
           	}

            $upUserInfo = array('nickname' => $nickName, 'is_activation' => 1);
           	$status   = $this->user->modifyUserByPassport($passPort, $upUserInfo);

            if ( !$status ) {
                $response = error(404);
                $response['data'] = array( 'passport' => $passPort, 'nickname' => $nickName );
                break;
            }
        } while (false);

        self::json_output($response);
    }

    /**
     * @name 游戏方用户登陆接口
     *
     * 200 ：帐号验证成功
     * 403 ：参数不全，不予验证
     * 404 ：帐号验证失败
     * 406 ：参数验证失败
     * 408 ：请求数据过期(请求时间超过10分钟)
     * 500 ：用户不存在
     * 501 ：昵称格式错误
     * 502 ：密码错误
     */
    public function login()
    {
		//error_reporting(E_ALL ^ E_NOTICE);

        $signKey     = $this->input->get_post('v');
        $userName    = $_REQUEST['u'];//$this->input->get_post('u');
		$encode = mb_detect_encoding($userName, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
		if ($encode != 'UTF-8') {
			$userName    = iconv($encode, 'utf-8', $userName);
		}
        $passWord    = $this->input->get_post('p');
        $loginType   = $this->input->get_post('l');  //1 昵称 0通行证
        $RequestTime = $this->input->get_post('d');
        //$backUrl     = $this->input->get_post('b');
        $sign        = md5($passWord.config_item('CLIENT_AUTH_KEY').$RequestTime.'010');

        if (empty($signKey) || empty($userName) || empty($passWord) || empty($RequestTime)) {
            self::json_output(array('msg' => 403));
            //self::json_output(array('msg' => 403, 'error'=>'参数不全，不予验证'));
            return ;
        }

        if ($signKey != $sign) {
            self::json_output(array('msg' => 406));
            //self::json_output(array('msg' => 406, 'error'=>'参数验证失败'));
            return ;
        }

        //调取棋魂昵称信息
        $this->load->model('user/model_user', 'user');
        $uInfo = array();
        if ($loginType) {
            $uInfo = $this->user->getUserByNickName($userName);
			
            if (empty ($uInfo)) {
                $this->load->model('model_weiqi_user', 'w_user');
                $nInfo = $this->w_user->getUserNickName($userName);
                if (empty ($nInfo)) {
                    self::json_output(array('msg' => 500));
                    //self::json_output(array('msg' => 500, 'error'=>'用户不存在'));
                } else {
					$this->load->database('bbs');
					//$salt = mt_rand('100000', '999999');
					//$pwd = md5(md5($input['password']) . $salt);
					$this->db->where('username', $nInfo['englishname']);
					$this->db->update('ucenter_members', array('nickname' => $userName));
					$this->db->close();

                    $tmp = array('nickname' => $nInfo['username'], 'is_activation' => 1);
                    $this->user->modifyUserByPassport($nInfo['englishname'], $tmp);
                    $loginType = 0;
                    $userName = $nInfo['englishname'];



                    //englishname  username
                }
            } else {
                $userName = $uInfo['passport'];
                $loginType = 0;
            }

        } else {
            //$uInfo = $this->user->getUserInfoByPassport($userName);
        }



        //1 昵称 0通行证
        $account_type = $loginType ? 3: 0;

        self::include_uc_lib();
        $userinfo = uc_user_login($userName, $passWord, $account_type, '', '', '');
        list($user['user_id'], $user['passport'], $user['nickname'], $user['password'], $user['email'], $duplicate) = $userinfo;
        if($user['user_id'] == -1)
        {
            self::json_output(array('msg' => 500));
            //self::json_output(array('msg' => 500, 'error'=>'用户不存在'));
            return ;
        } else if ($user['user_id'] == -2) {
            self::json_output(array('msg' => 502));
            //self::json_output(array('msg' => 502, 'error'=>'密码错误'));
            return ;
        }

        self::json_output(array('msg' => 200, 'username' => $userName, 'nickname' => $user['nickname'], 'email' => $user['email']));
        //self::json_output(array('msg' => 200, 'error'=>'登录成功', 'username' => $userName, 'nickname' => $user['nickname'], 'email' => $user['email']));
    }
}
